package com.ysxsoft.wdg.pay;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;

import com.alipay.sdk.app.PayTask;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.ysxsoft.wdg.MyApplication;

import java.util.Map;

/**
 * 支付工具类
 */
@SuppressLint("StaticFieldLeak")
public class PayUtils {
    private static final String TAG = "PayUtils";

    /**
     * 订单状态
     */
    public static final int PAY_STATE_PAID= 1020;
    public static final int PAY_STATE_TO_PAY = 1010;

    /**
     * 支付类型
     */
    public static final int PAY_TYPE_WX = 1;
    public static final int PAY_TYPE_ALI = 2;

    final static int SDK_PAY_FLAG = 1001;

    private static PayUtils instance;
    private static Context sContext;

    private PayUtils() {
    }

    public static PayUtils getInstance(Context context) {
        if (instance == null) {
            instance = new PayUtils();
        }
        sContext = context;
        return instance;
    }

    public static void pay(Activity activity,int payType, String result,WxPayBean payBean) {
        switch (payType) {
            case PAY_TYPE_WX:
                toWXPay(result);
                break;
            case PAY_TYPE_ALI:
                toAliPay(activity,result);
                break;
        }
    }

    private static void toAliPay(final Activity activity, String result) {
        result = result.replace("&amp;", "&");
        final String finalResult = result;
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                PayTask alipay = new PayTask(activity);
                Map<String, String> map = alipay.payV2(finalResult, true);
                Message msg = sHandler.obtainMessage();
                msg.what = SDK_PAY_FLAG;
                msg.obj = map;
                sHandler.sendMessage(msg);
            }
        };
        //异步调用
        Thread payThread = new Thread(runnable);
        payThread.start();
    }

    private static void toWXPay(final String result) {
        IWXAPI api = WXAPIFactory.createWXAPI(sContext, MyApplication.WXAppId);
        api.registerApp(MyApplication.WXAppId);//将app注册到微信
        PayReq request = new PayReq();
        request.appId = "wxfe2fa2f264353d7d3";
        request.partnerId = "1494934532";
        request.prepayId = "wx201802011023453926020588351720";
        request.packageValue = "Sign=WXPay";
        request.nonceStr = "4cdCo3o4453xhGPpv";
        request.timeStamp = System.currentTimeMillis() / 1000 + "";
        request.sign = "F8A42CF827345377A34646ADD9E321FAB4";
        boolean send = api.sendReq(request);
    }

    public static void toWxPay(WxPayBean wxPayBean){
        IWXAPI api = WXAPIFactory.createWXAPI(sContext, MyApplication.WXAppId);
        api.registerApp(MyApplication.WXAppId);//将app注册到微信
        PayReq request = new PayReq();
        request.appId = wxPayBean.getAppid();
        request.nonceStr = wxPayBean.getNoncestr();
        request.packageValue = wxPayBean.getPackageX();
        request.partnerId = wxPayBean.getPartnerid();
        request.prepayId = wxPayBean.getPrepayid();
        request.timeStamp = wxPayBean.getTimestamp();
        request.sign = wxPayBean.getSign();
        api.sendReq(request);
    }

    public static void toWxPay(WxPayBean wxPayBean,PayResultListener listener){
        IWXAPI api = WXAPIFactory.createWXAPI(sContext, MyApplication.WXAppId);
        api.registerApp(MyApplication.WXAppId);//将app注册到微信
        PayReq request = new PayReq();
        request.appId = wxPayBean.getAppid();
        request.nonceStr = wxPayBean.getNoncestr();
        request.packageValue = wxPayBean.getPackageX();
        request.partnerId = wxPayBean.getPartnerid();
        request.prepayId = wxPayBean.getPrepayid();
        request.timeStamp = wxPayBean.getTimestamp();
        request.sign = wxPayBean.getSign();

        PayListenerUtils.getInstance(sContext).addListener(listener);
        api.sendReq(request);
    }

    /**
     * 支付宝状态
     * 9000 订单支付成功
     * 8000 正在处理中，支付结果未知（有可能已经支付成功），请查询商户订单列表中订单的支付状态
     * 4000 订单支付失败
     * 5000 重复请求
     * 6001 用户中途取消
     * 6002 网络连接出错
     * 6004 支付结果未知（有可能已经支付成功），请查询商户订单列表中订单的支付状态
     * 其它 其它支付错误
     */
    @SuppressLint("HandlerLeak")
    private static Handler sHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case SDK_PAY_FLAG:
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    String result = payResult.getResult();
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        PayListenerUtils.getInstance(sContext).addSuccess();
                    } else if (TextUtils.equals(resultStatus, "6001")) {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        PayListenerUtils.getInstance(sContext).addCancel();
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        PayListenerUtils.getInstance(sContext).addError();
                    }
                    break;
            }
        }
    };

}
